﻿using HDLogCenter.Infrastructure.Models;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace HDLogCenter.Infrastructure.Utils
{
    internal class LogMonitorHelper
    {
        private readonly DingTalkRobotHelper _dingTalkRobot;
        private readonly ConcurrentDictionary<string, List<DateTime>> _errorLogTracker = new ConcurrentDictionary<string, List<DateTime>>();
        private readonly ConcurrentDictionary<string, DateTime> _lastAlertTime = new ConcurrentDictionary<string, DateTime>();

        public LogMonitorHelper(DingTalkRobotHelper dingTalkRobot)
        {
            _dingTalkRobot = dingTalkRobot;
        }

        public async Task HandleLogAsync(Dictionary<string, object> log)
        {
            if (!log.TryGetValue("Level", out var level) || level?.ToString() != "Error")
                return;

            string project = log.ContainsKey("ProjectName") ? log["ProjectName"].ToString() : "Unknown";
            var now = DateTime.UtcNow;

            var list = _errorLogTracker.GetOrAdd(project, _ => new List<DateTime>());
            lock (list)
            {
                list.Add(now);
                // 只保留最近一分钟
                list.RemoveAll(t => (now - t).TotalSeconds > 60);

                if (list.Count >= 5)
                {
                    // 判断冷却时间（5分钟）
                    if (!_lastAlertTime.ContainsKey(project) || (now - _lastAlertTime[project]).TotalMinutes > 5)
                    {
                        _ = SendDingTalkAlertAsync(project, list.Count);
                        _lastAlertTime[project] = now;
                    }
                }
            }
        }

        private async Task SendDingTalkAlertAsync(string project, int count)
        {
            string content = $"⚠️ 项目【{project}】在 1 分钟内产生 {count} 条错误日志，请及时关注！";
            var result = await _dingTalkRobot.SendTextAsync(content, isAtAll: true);
            Console.WriteLine($"钉钉告警发送结果: {result}");
        }
    }
}